<?php

class Utils
{

    public static function writeJson($code = 0, $msg = 'success', $data = []) {
        $result = array(
            'code' => $code ?: 0,
            'msg' => $msg ?: 'success',
            'data' => $data ?: []
        );
        return json_encode($result);
    }

    /**
     *  加锁
     */
    public static function task_lock($redis){
        $expire = 2;
        $lock_key ='task_get_run';
        $lock = $redis->setNX($lock_key , time());//设当前时间
        if($lock){
            $redis->expire($lock_key,  $expire); //如果没执行完 2s锁失效
        }
        if(!$lock){//如果获取锁失败 检查时间
            $time = $redis->get($lock_key);
            if(time() - $time  >=  $expire){//添加时间戳判断为了避免expire执行失败导致死锁 当然可以用redis自带的事务来保证
                $redis->rm($lock_key);
            }
            $lock =  $redis->setNX($lock_key , time());
            if($lock){
                $redis->expire($lock_key,  $expire); //如果没执行完 2s锁失效
            }
        }
        return $lock;
    }

    /**
     *  解锁
     */
    public static function task_unlock($redis){
        $lock_key = 'task_get_run';
        $redis->rm($lock_key);
    }
}